/*
    地图界面
 */

import React from 'react';
import {
  View,
  FlatList,
  RefreshControl,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  ScrollView,
  TouchableHighlight,
  Dimensions,
  Platform,
  Keyboard,
} from 'react-native';
import StoreShop from '../module/StoreShop';
import {BProps, BState, HeaderView, BaseComponent, Styled} from '../../index';
import {NoDataList, ItemList} from './ItemListLayout';
import { R } from '../../../core';
import {IconFont } from 'enoad-common/src/index';
import _ from 'lodash';
import SearchList from '../../SearchList';
import ShopCard from '../../StoreShopCard';
import EntityDetail from '../../EntityDetailPage';
import {v4 as uuidv4} from 'uuid';
const {width, height} = Dimensions.get('window');

import BaseModal from '../../../core/modal/bottom/BaseModal';
import FilterLayout from './FilterLayout';
import SortLayout from './SortLayout';
const NativeStoreMallModule = require('../../../core/modules/NativeStoreMallModule');



interface IProps extends BProps {
  data?: any;
}

interface IState extends BState {
  isLoading: boolean;
  isShowDialog: boolean;
  filterLayoutShow: boolean;
  filterTop: number;
  showSortLayout: boolean;
}

export default class StoreShopComponent extends BaseComponent<IProps, IState> {
  shopData: StoreShop;
  selectItem: any;

  constructor(props: BProps) {
    super(props);
    this.state = {
      isLoading: false,
      isShowDialog: false,
      filterLayoutShow: false,
      filterTop: 0,
      showSortLayout: false,
    };
    this.shopData = new StoreShop('Visit');
    this.props.actions.init(this.props.componentId, this.shopData);
  }

  shopList = (data: any, layout: object) => {
    if (data && data.showDatas && data.showDatas.length > 0) {
      //有值进行展示
      return (
        <FlatList
          keyboardShouldPersistTaps="always"
          style={{flex: 1}}
          data={data.showDatas}
          keyExtractor={(item, index) => index.toString()}
          renderItem={({item, index}) =>  this.listItem(item, index, layout)}
          refreshControl={
            <RefreshControl
              title={'加载中...'}
              colors={['red']} //此颜色无效
              tintColor={'orange'}
              titleColor={'red'} //只有ios有效
              refreshing={this.state.isLoading}
              onRefresh={() => {}}
            />
          }
        />
      );
    } else {
      return (
        <NoDataList
          componentId={this.props.componentId}
          actions={this.props.actions}
          openDetail={this.openDetail}
          addCart={this.addCart}
        />
      );
    }
  };

  listItem = (item: any, index: number, layout: any) => {
    //根据业务类型的key获取对应数据
    let layouts = new Array();
    //线路数据集合
    layouts.push(
      <ItemList
        key={index.toString() + item.id}
        dataSource={item}
        showItems={layout}
        actions={this.props.actions}
        componentId={this.props.componentId}
        storeShop={this.shopData}
        openDetail={this.openDetail}
        addCart={this.addCart}
      />,
    );
    return layouts;
  };

  openDetail = (item: any) => {
    console.log("[openDetail]",this.props)
    this.props.navigator &&
      this.props.navigator.push({
        component: EntityDetail,
        param: {item},
      });
  };

  addCart = (item: any) => {
    NativeStoreMallModule.openDialog((param: { isFinish: string, msg: string }) => {
      console.log("【触发结果】",param)
    });
  };
  /**
   * 顶部标题栏
   * @returns
   */
  renderCenter = () => {
    return (
      <Text
        numberOfLines={1}
        style={[R.styles.navigationTitleFont, {color: '#262626'}]}>
        {'全部商品'}
      </Text>
    );
  };
  /**
   * 搜索入口
   */
  searchView() {
    return (
      <View style={{flexDirection: 'column'}}>
        <View style={Styled.SearchView.item}>
          <TouchableOpacity
            style={{
              flexDirection: 'row',
              flex: 1,
              paddingLeft: 10,
              alignItems: 'center',
            }}
            onPress={() => {
              this.setState({isShowDialog: true});
            }}>
            <Text style={[Styled.SearchView.shop_search_text, {fontSize: 13}]}>
              {'客户名称'}
            </Text>
            <Text style={[Styled.SearchView.shop_search_text, {fontSize: 13}]}>
              {'｜'}
            </Text>
            <Text
              style={[
                Styled.SearchView.shop_search_text,
                {fontSize: 13, paddingRight: 10},
              ]}>
              {'价格表名称'}
            </Text>
            <IconFont name={'xiala'} size={6} color={'#4E80F5'} />
          </TouchableOpacity>

          <TouchableOpacity
            style={[
              Styled.SearchView.search,
              {height: 35, alignItems: 'center', padding: 10},
            ]}
            onPress={() => {
              this.props.navigator &&
                this.props.navigator.push({
                  component: SearchList,
                  param: {title: '搜索'},
                });
            }}>
            <View style={{position: 'absolute', right: 0, marginRight: 15}}>
              <IconFont name={'sousuo'} size={20} color={'#6A7280'} />
            </View>
          </TouchableOpacity>
          <TouchableOpacity
            style={Styled.SearchView.shop_card}
            onPress={() => {
              this.props.navigator &&
                this.props.navigator.push({
                  component: ShopCard,
                  param: {
                    title: '购物车',
                    cardData: this.getKey('shopCard'),
                    cardLayout: this.getKey('layout'),
                  },
                });
            }}>
            {this.IconWithBadge()}
          </TouchableOpacity>
        </View>
        <View style={{height: 1, backgroundColor: '#F1F2F5'}} />
      </View>
    );
  }

  /**
   * 选项卡入口
   */
  selectView(layout: any) {
    return (
      <View style={{flexDirection: 'column'}}>
        <View style={[Styled.SearchView.item, {padding: 5}]}>
          {layout && layout.defaultFilterItems ? (
            <FilterLayout
              componentId={this.props.componentId}
              itemClick={this.onItemPress}
              item={layout.defaultFilterItems}
            />
          ) : null}

          {layout && layout.sortItems ? (
            <SortLayout
              componentId={this.props.componentId}
              itemClick={this.onSortItemPress}
              item={layout.sortItems}
            />
          ) : null}
        </View>
        <View style={{height: 1, backgroundColor: '#F1F2F5'}} />
      </View>
    );
  }

  onItemPress = (py: number, item: any) => {
    if (
      this.selectItem &&
      this.selectItem.apiKey == item.apiKey &&
      this.state.filterLayoutShow
    ) {
      //第二次点击相同窗口
      this.setState({
        filterLayoutShow: !this.state.filterLayoutShow,
        showSortLayout: false,
        filterTop: py,
      });
    } else {
      this.setState({
        filterLayoutShow: true,
        showSortLayout: false,
        filterTop: py,
      });
    }
    this.selectItem = item;
  };

  onSortItemPress = (py: number, item: any) => {
    this.setState({
      showSortLayout: !this.state.showSortLayout,
      filterLayoutShow: false,
      filterTop: py,
    });
  };

  _onStartShouldSetResponderCapture(event: any) {
    let target = event.nativeEvent.identifier;
    if (Platform.OS !== 'android') {
      Keyboard.dismiss();
    }
    return false;
  }

  selectItemView(item: any) {
    let FilterLayoutView = (
      <View style={{backgroundColor: 'white', alignItems: 'center'}}>
        <Text style={{padding: 10}}>{'请选择'}</Text>
        <Text style={{padding: 10}}>{'请选择'}</Text>
        <Text style={{padding: 10}}>{'请选择'}</Text>
        <Text style={{padding: 10}}>{'请选择'}</Text>
        <Text style={{padding: 10}}>{'请选择'}</Text>
        <Text style={{padding: 10}}>{'请选择'}</Text>
        <Text style={{padding: 10}}>{'请选择'}</Text>
        <Text style={{padding: 10}}>{'请选择'}</Text>
      </View>
    );
    return (
      <View
        style={{flex: 0, backgroundColor: 'white'}}
        onStartShouldSetResponderCapture={
          this._onStartShouldSetResponderCapture
        }>
        <ScrollView
          keyboardShouldPersistTaps={'always'}
          style={{
            flex: 0,
            paddingLeft: 15,
            paddingRight: 15,
            maxHeight: 290,
          }}>
          {FilterLayoutView}
        </ScrollView>
        <View style={{height: 1, backgroundColor: '#F1F2F5'}} />
        <View style={{flex: 0, width: width, flexDirection: 'row'}}>
          <TouchableHighlight
            underlayColor="#eff3f6"
            onPress={() => {}}
            activeOpacity={1}
            style={{backgroundColor: '#fff'}}>
            <View
              style={{
                flex: 0,
                height: 48,
                width: width / 2,
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <Text style={{fontSize: 16, color: '#4e80f5'}}>{'清除条件'}</Text>
            </View>
          </TouchableHighlight>
          <TouchableHighlight
            style={{backgroundColor: '#4e80f5'}}
            activeOpacity={1}
            underlayColor="#4197d9"
            onPress={() => {}}>
            <View
              style={{
                flex: 0,
                height: 48,
                width: width / 2,
                alignItems: 'center',
                justifyContent: 'center',
              }}>
              <Text style={{fontSize: 16, color: '#fff'}}>{'确定'}</Text>
            </View>
          </TouchableHighlight>
        </View>
      </View>
    );
  }

  selectSortItemView(item: any) {
    let arry = [];
    for (let index = 0; index < item.length; index++) {
      const element = item[index];
      arry.push(
        <Text key={element.id} style={{padding: 10}}>
          {element.label}
        </Text>,
      );
    }
    let FilterLayoutView = (
      <View style={{backgroundColor: 'white', alignItems: 'center'}}>
        {arry}
      </View>
    );
    return (
      <View style={{flex: 0, backgroundColor: 'white'}}>
        <ScrollView
          keyboardShouldPersistTaps={'always'}
          style={{
            flex: 0,
            paddingLeft: 15,
            paddingRight: 15,
            maxHeight: 290,
          }}>
          {FilterLayoutView}
        </ScrollView>
        <View style={{height: 1, backgroundColor: '#F1F2F5'}} />
      </View>
    );
  }

  confirmSelect = (item: any) => {
    this.setState({isShowDialog: false});
  };
  cancelSelect = () => {
    this.setState({isShowDialog: false});
  };
  IconWithBadge() {
    let shopCard = this.getKey('shopCard');
    if (shopCard && shopCard.length > 0) {
      return (
        <View>
          <IconFont name={'gouwuchekong'} size={20} color={'#6A7280'} />
          <View
            style={{
              position: 'absolute',
              right: -6,
              top: 0,
              backgroundColor: 'red',
              borderRadius: 10,
              width: 15,
              height: 15,
              alignItems: 'center',
            }}>
            <Text style={{color: 'white', fontSize: 10, fontWeight: 'bold'}}>
              {shopCard.length > 99 ? '99+' : shopCard.length}
            </Text>
          </View>
        </View>
      );
    } else {
      return <IconFont name={'gouwuchekong'} size={20} color={'#6A7280'} />;
    }
  }

  getKey(key: string) {
    return this.props.state.getIn([
      'instances',
      this.props.componentId,
      `${key}`,
    ]);
  }

  render() {
    let lineTop = Platform.OS === 'ios' ? -2 : -0.8;
    let data = this.getKey('data');
    let layout = this.getKey('layout');
    let FilterView = null;
    if (this.state.filterLayoutShow) {
      FilterView = this.selectItemView(layout && layout.defaultFilterItems);
    }
    let SortView = null;
    if (this.state.showSortLayout) {
      SortView = this.selectSortItemView(layout && layout.sortItems);
    }
    return (
      <View style={{flex: 1}}>
        {/* <HeaderView
          componentId={this.props.componentId}
          backgroundColor={"#ffffff"}
          leftButtonColor={"#4A4B6D"}
          renderCenter={this.renderCenter}
          navigator={this.props.navigator}
        /> */}
        {this.searchView()}
        {this.selectView(layout)}
        {this.shopList(data, layout)}
        {(this.state.filterLayoutShow || this.state.showSortLayout) && (
          <View
            style={{
              width: width,
              height: height - this.state.filterTop,
              position: 'absolute',
              top: this.state.filterTop + 40,
              right: 0,
              left: 0,
              marginTop: lineTop,
            }}>
            <View
              style={{flexDirection: 'row', backgroundColor: 'white'}}></View>
            {this.state.showSortLayout ? SortView : FilterView}
            <TouchableWithoutFeedback
              onPress={() => {
                this.setState({
                  filterLayoutShow: false,
                  showSortLayout: false,
                });
              }}>
              <View
                style={{
                  flex: 0,
                  backgroundColor: '#000',
                  opacity: 0.5,
                  height: height,
                }}
              />
            </TouchableWithoutFeedback>
          </View>
        )}

        <BaseModal
          title={''}
          content={[
            {id: uuidv4(), name: '客户', select: '请选择'},
            {id: uuidv4(), name: '价格表', select: '请选择'},
          ]}
          confirm={this.confirmSelect}
          cancel={this.cancelSelect}
          visible={this.state.isShowDialog}
        />
      </View>
    );
  }
}
